<?php
date_default_timezone_set("America/Mexico_City");
define("BASE_PATH", "C://xampp//htdocs//meweb//");

set_time_limit(0);

function createFolder($folderName) {
    $folderName = BASE_PATH;
    if (!is_dir($folderName)) {
        @mkdir($folderName, 0700);
    } else {
        echo "Ya existe ese directorio\n";
    }
}

function save_img($image) {

    $img_file = file_get_contents($image);

    $image_path = parse_url($image);
    $img_path_parts = pathinfo($image_path['path']);

    $filename = $img_path_parts['filename'];
    $img_ext = $img_path_parts['extension'];

    $path = date("d-m-Y_H") . "/";
    $path1 = mkdir($path, 0755);

    #
    generateMark($filename,$path);
    #
    
    $filex = $path . $filename . "." . $img_ext;
    $fh = fopen($filex, 'w');
    fputs($fh, $img_file);
    fclose($fh);
    return filesize($filex);
}

function getHtmlComponente($file) {
    $html = file_get_contents($file);
    preg_match("/view_bline(.*)/", $html, $htmlFinal);
    $partes = explode(",", $htmlFinal[1]);
    $idImage = str_replace("'", "", $partes[2]);
    $idImage = str_replace(");", "", $idImage);
    return $idImage;
}

$sx = simplexml_load_file('http://www.desktopwallpapers.ru/new-wallpapers.xml');
$salida = "";


/*
  echo "<pre>";
  print_r($sx);
  die;
 * 
 */


foreach ($sx->channel as $chanel) {
    foreach ($chanel->item as $elemento) {
        $img = $elemento->link;
        $getPartImg = explode("?pic=", $elemento->link);
        $imageId = $getPartImg[1];


        #Generar categoría
        #.ru/anime/view/
        $pathCategory = explode(".ru/", $elemento->link);
        $pathCategory2 = explode("/view/", $pathCategory[1]);
        $category = $pathCategory2[0];

        $fotosArray[] = array("id" => $imageId, "category" => $category);
    }
}



if (is_array($fotosArray)) {
    foreach ($fotosArray AS $item) {


        #echo "<br>=>" . $item['id'] . "------" . $item['category'];
        $cat = $item['category'];
        $fotoID = $item['id'];
        $id = getHtmlComponente("http://www.desktopwallpapers.ru/" . $cat . "/view/?pic=" . $fotoID);
        #-1600.jpg
        echo $imgSrc = "http://img.desktopwallpapers.ru/" . $cat . "/pics/" . $id . "-1600.jpg";
        #echo $imgSrc = "http://img.desktopwallpapers.ru/".$cat."/pics/".$id.".jpg";
        save_img($imgSrc);
        die;
    }
} else {
    echo "Algo esta fallando";
}
?>
<br>
<hr>